package com.zyx.netty.handler;

import com.zyx.service.RequestMsgService;
import com.zyx.service.RequestMsgServiceResolver;
import com.zyx.utils.DynamicMsgUtils;
import com.zyx.constants.ChannelMap;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import static com.zyx.constants.Constants.MPSP_URI;

/**
 * 接收所有的http请求：终端请求 业务平台请求共用handler
 * 根据请求报文 和 请求URL进行响应后续处理
 *
 * @author DQing
 * @version 1.0
 * @className UpControlHandler
 * @date 2020/3/25 18:09
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class DeviceRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Autowired
    private RequestMsgServiceResolver requestMsgServiceResolver;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("终端设备 {} 上线了",channel.remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("终端设备 {} 下线了",channel.remoteAddress());
        ChannelMap.removeDeviceChannelByName(ctx.channel().id().asLongText());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        String uri = msg.uri();
        MDC.put(MPSP_URI,uri);
        String content = msg.content().toString(CharsetUtil.UTF_8);
        log.info("收到请求报文，请求URI={}, 请求报文={}",uri,content);
        RequestMsgService requestMsgService = requestMsgServiceResolver.getRequestMsgService(uri);
        if(StringUtils.isEmpty(requestMsgService)){
            requestMsgService.parseMsg(ctx,content);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        log.info(cause.getMessage());
        cause.printStackTrace();
    }

}
